from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from .form import FormRegister
from .form import FormLogin
from .models import Image
from .models import Usermsg
from .models import Article
from .models import Typemsg
from .models import Comment
import os

# D:\programming_python\week12_hw_web\python_study_site\home_0317\templates\static_html
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

@csrf_exempt
def upload_img(request):
    if request.method == 'POST':
        new_img = Image(
            img=request.FILES.get('img'),
            name=request.FILES.get('img').name
        )
        new_img.save()
    return render(request, 'img_tem/uploading.html')

@csrf_exempt
def show_img(request):
    imgs = Image.objects.all()
    content = {
        'imgs':imgs,
    }
    for i in imgs:
        print(i.img.url)
    return render(request, 'img_tem/showimg.html', content)


def register(request):
    # if register.session.has_key("user_on_line"):
    #     return HttpResponseRedirect('/')
    if request.method == 'POST':
        form = FormRegister(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            pwd = form.cleaned_data['pwd']
            phone = form.cleaned_data['phone']
            sex = form.cleaned_data['sex']
            email = form.cleaned_data['email']
            Usermsg.objects.create(name=name, pwd=pwd, email=email, sex=sex, phone=phone,
                                   privilege=1, articles=0, visits=0, icon='user_icons/zym.jpg', icon_name='zym.jpg')
            return HttpResponse(f'你的注册信息为： {name} {email} 注册成功!')
    else:
        form = FormRegister()
        return render(request, 'register_form.html', {'form': form})
    pass



def login(request):
    if request.session.has_key('user_on_line'):
        # return HttpResponseRedirect('/news_home.html')
        return HttpResponseRedirect('/index')
    elif request.method == 'POST':
        name = request.POST['name']
        pwd = request.POST['pwd']
        is_login = Usermsg.objects.filter(name__exact=name, pwd__exact=pwd)
        if (is_login):
            request.session['user_on_line'] = name
            HttpResponse("Login success!")
            # return HttpResponseRedirect('/news_home.html')
            return HttpResponseRedirect('/index')
        else:
            return HttpResponse("Login fail...")
    else:
        form = FormLogin()
        return render(request, 'login.html', {'form': form})
    pass


def logout(request):
    del request.session['user_on_line']
    # HttpResponse("Logout OK!")
    # time.sleep(5)
    return HttpResponseRedirect('/index')
    pass


def index(request):
    if request.session.has_key('user_on_line'):
        nav1 = request.session['user_on_line']
        nav2 = '/user_detail'
        nav3 = '退出'
        nav4 = '/logout'
    else:
        nav1 = '注册'
        nav2 = '/register'
        nav3 = '登陆'
        nav4 = '/login'
    typename = Typemsg.objects.values('id', 'typename')
    article  = Article.objects.values('id', 'title', 'author', 'detail', 'visits', 'comments')[:3]
    return render(request, 'index.html', {'article': article, 'typename': typename, 'nav1': nav1, 'nav2':nav2, 'nav3':nav3, 'nav4':nav4})
    pass


@csrf_exempt
def user_msg(request):
    if request.session.has_key('user_on_line'):
        this_name = request.session['user_on_line']
        this_user = list(Usermsg.objects.filter(name=this_name).values('id', 'name', 'email', 'phone',
                                                                       'privilege', 'sex', 'articles', 'icon', 'icon_name'))[0]
        return render(request, 'user_detail.html', {'this_user': this_user, })
        pass
    else:
        pass

@csrf_exempt
def upload_icon(request):
    if request.method == 'POST':
        this_name = request.session['user_on_line']
        # this_user = list(Usermsg.objects.filter(name=this_name).values('icon', 'icon_name'))[0]
        this_user = Usermsg.objects.get(name=this_name)
        this_user.icon  = request.FILES.get('img')
        this_user.icon_name = request.FILES.get('img').name

        line = ''
        print('user_priviliege ------------------------------' + str(this_user.privilege))
        if (this_user.privilege < 2):
            this_user.privilege = 2
            line = '你现在可以发表博文了'

        this_user.save()
        # Usermsg.objects.filter(name=this_user).update(privilege=2)

        return HttpResponse(f"上传头像成功，请返回用户详情页刷新！{line}")
    else:
        return render(request, 'img_tem/uploading.html')


def article(request, aid):
    if request.method == 'GET':
        path = os.path.join(BASE_DIR, 'home_0317/templates/static_html/')
        if os.path.exists(path + str(aid) + '.html'):
            return render(request, path + str(aid) + '.html')
        else:
            print(type(aid))
            print("Aid = " + str(aid))
            thisarticle = list(Article.objects.filter(id=int(aid)).values('id', 'title', 'author', 'detail', 'content', 'visits', 'comments'))[0]
            comments = Comment.objects.filter(aid=int(aid))
            # user = Usermsg.objects.filter()
            return render(request, 'detail.html', {'thisarticle': thisarticle, 'comments': comments})
    elif request.method == 'POST':
        if request.session.has_key('user_on_line'):
            # aid = request.POST['']
            comment_text = request.POST['message']
            uid = list(Usermsg.objects.filter(name=request.session['user_on_line']).values())[0]['id']
            comment_obj = Comment(uid=int(uid), content=comment_text, aid=int(aid))
            comment_obj.save()
            return HttpResponseRedirect(f'{aid}')
        else:
            return HttpResponseRedirect('login/')


def class_list_python(request, atype):
    if request.session.has_key('user_on_line'):
        nav1 = request.session['user_on_line']
        nav2 = '/user_detail'
        nav3 = '退出'
        nav4 = '/logout'
    else:
        nav1 = '注册'
        nav2 = '/register'
        nav3 = '登陆'
        nav4 = '/login'
    print(f"FFFFFFFFFFFFFFFFFFFFFFFF atype : {atype}")
    ntype = int(atype[0])
    typename = Typemsg.objects.values('id', 'typename')
    # ntype 1 == 新闻  2 ==  技术 3 == 职场
    this_type = Typemsg.objects.get(id=ntype)
    # articles = Article.objects.filter(atype=this_type.typename)
    articles = Article.objects.filter(atype=str(ntype))
    return render(request, 'list.html',
                  {'article': articles, 'typename': typename, 'nav1': nav1, 'nav2': nav2, 'nav3': nav3, 'nav4': nav4})


def post_articles(request):
    if request.session.has_key('user_on_line') == False:
        return HttpResponseRedirect('/login')
    else:
        nav1 = request.session['user_on_line']
        nav2 = '/user_detail'
        nav3 = '退出'
        nav4 = '/logout'

        typeall = Typemsg.objects.values('id', 'typename')
        typeid = []
        typename = []
        for item in typeall:
            typeid.append(item['id'])
            typename.append(item['typename'])
        type_zip = zip(typeid, typename)
        user = list(Usermsg.objects.filter(name=request.session['user_on_line']).values())[0]
        uid = user['id']
        uname = user['name']
        uprivilege = user['privilege']
        if (uprivilege < 2):
            return HttpResponseRedirect('/index')
        if request.method == 'POST':
            content = request.POST['content']
            thistypeid = request.POST['typeid']
            postname = request.POST['title']
            detail = request.POST['detail']
            print(f'post_articles ------------- {thistypeid}')
            Article.objects.create(title=postname, content=content, tid=thistypeid, uid=uid, author=postname,
                                   detail=detail, visits=0, comments=0, atype=thistypeid)
            return HttpResponseRedirect('/index')
        return render(request, 'postarticles.html', {'type_zip': type_zip, 'nav1': nav1, 'nav2': nav2, 'nav3': nav3, 'nav4': nav4})
    pass


def static_all(request, thepage):
    import urllib.request

    print('DDDDDDDDDDDDDDDDDDDDDDDDDDDir = ' + BASE_DIR)
    path = os.path.join(BASE_DIR, 'home_0317/templates/static_html/')
    for i in range(0, int(thepage)):
        try:
            url = f'http://127.0.0.1:8000/articles/{i}'
            urllib.request.urlretrieve(url, filename=path + str(i) + '.html')
            pass
        except Exception as err:
            print(err)

    return HttpResponse("伪静态化陈功！")


def alist(request):
    if request.session.has_key('user_on_line'):
        nav1 = request.session['user_on_line']
        nav2 = '/user_detail'
        nav3 = '退出'
        nav4 = '/logout'
    else:
        nav1 = '注册'
        nav2 = '/register'
        nav3 = '登陆'
        nav4 = '/login'
    typename = Typemsg.objects.values('id', 'typename')
    article  = Article.objects.values('id', 'title', 'author', 'detail', 'visits', 'comments')
    return render(request, 'list.html', {'article': article, 'typename': typename, 'nav1': nav1, 'nav2':nav2, 'nav3':nav3, 'nav4':nav4})

